package com.minglead.springboot.platform.sys.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.minglead.springboot.common.crud.BaseController;
import com.minglead.springboot.common.persistence.Page;
import com.minglead.springboot.common.utils.StringUtils;
import com.minglead.springboot.platform.sys.entity.Area;
import com.minglead.springboot.platform.sys.entity.Office;
import com.minglead.springboot.platform.sys.service.OfficeService;
import com.minglead.springboot.platform.sys.utils.ActionResponse;

/**
 * 机构Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/office")
public class OfficeController extends BaseController {

	@Autowired
	private OfficeService officeService;

	@ModelAttribute("office")
	public Office get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return officeService.get(id);
		} else {
			return new Office();
		}
	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = { "" })
	public String index() {
		// model.addAttribute("list", officeService.findAll());
		return "modules/sys/officeIndex";
	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = { "list" })
	public String list(String id, Model model) {
		model.addAttribute("id", id);
		return "modules/sys/officeList";
	}

	@RequestMapping(value = "loadData")
	public void loadData(String id, HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("name");
		String areaName = request.getParameter("areaName");

		Office office = new Office();
		Area area = new Area();
		area.setName(areaName);
		office.setName(name);
		office.setArea(area);

		office.setId(id);
		Page<Office> page = new Page<Office>(request, response);
		Page<Office> template = this.officeService.findPage(page, office);
		renderGrid(request, response, template);
	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "form")
	public String form(Office office, Model model) {
		//添加机构
		if (StringUtils.isEmpty(office.getId()) && office.getParent() != null) {
			Office parent = officeService.get(office.getParent().getId());
			office.setParent(parent);
			office.setArea(parent.getArea());
			office.setSort(0);
		}else if(!StringUtils.isEmpty(office.getId())){
			//修改机构
			
		}
		model.addAttribute("office", office);
		return "modules/sys/officeForm";
	}

	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "save")
	public String save(Office office, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, office)) {
			return form(office, model);
		}
		officeService.save(office);
		addMessage(redirectAttributes, "保存机构'" + office.getName() + "'成功");
		return "redirect:" + contextPath + adminPath + "/sys/office/list";
	}
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "delete")
	public void delete(String id ,HttpServletResponse response) {
		ActionResponse r = new ActionResponse(1,"操作成功！");
		if(StringUtils.isEmpty(id)){
			r.setMessage("删除失败,id不能为null");
			this.responseObject(r, response);
			return;
		}
		String[] _id = id.split(",");
		for(String id0:_id){			
			Office hasOffice = officeService.get(id0);
			if(hasOffice!=null&&"0".equals(hasOffice.getParentId())){
				this.responseObject(r, response);
				r.setMessage("删除包含根节点，操作失败！");
				return;
			}
			officeService.delete(hasOffice);
		}
		this.responseObject(r, response);
	}
	/**
	 * 获取机构JSON数据。
	 * 
	 * @param extId
	 *            排除的ID
	 * @param type
	 *            类型（1：公司；2：部门/小组/其它：3：用户）
	 * @param grade
	 *            显示级别
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId,
			@RequestParam(required = false) String type,
			@RequestParam(required = false) Boolean isAll, HttpServletResponse response) {
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
		List<Office> list = officeService.findList(isAll);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			if ((StringUtils.isBlank(extId)
					|| (extId != null && !extId.equals(e.getId())))
					&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))) {
				Map<String, Object> map = new HashMap<String,Object>();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
/*				map.put("pIds", e.getParentIds());*/
				map.put("name", e.getName());
				if (type != null && "3".equals(type)) {
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}

}
